package de.tayrracer.geoobjects;

import de.tayrracer.Math;

public class Triangle extends BaseObject {
	private double[] v1 = null;
	private double[] v2 = null;
	private double[] v3 = null;
	
	public Triangle (double[] v1,double[] v2,double[] v3)
	{
		this.v1 = v1;
		this.v2 = v2;
		this.v3 = v3;
	}
	
	public double[] isCut(double[] origin, double[] direction){
		double[] e1 = Math.subtractVectors(v2, v1);
		double[] e2 = Math.subtractVectors(v3, v1);
		double[] t = Math.subtractVectors(origin, v1);
		double[] p = Math.crossProduct(direction, e2);
		double[] q = Math.crossProduct(t, e1);
		double factor = 1.0/Math.scalarProduct(e1, p);
		
		double lam = factor*Math.scalarProduct(q, e2);
		double u = factor*Math.scalarProduct(p, t);
		double v = factor*Math.scalarProduct(q, direction);
		
		if(u >= 0 && v >= 0 && u+v<=1)
			return Math.addVectors(origin, Math.scalarMult(lam, direction));
		
		return null;
	}
	
	public Ray getColorForCut(double[] origin, double[] direction, BaseObject[] objects, int count){
		double[] cutPoint = isCut(origin,direction);
		if (cutPoint!= null){
			Ray result = new Ray();
			result.position = cutPoint;
			result.rayColor = objectColor;
			return result;
		}
		return null;
	}
}
